package com.bigfans.cartservice.api.clients;

import com.bigfans.api.clients.ServiceRequest;
import com.bigfans.cartservice.CartApplications;
import com.bigfans.cartservice.model.Product;
import com.bigfans.cartservice.model.ProductSpec;
import com.bigfans.framework.utils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @author lichong
 * @create 2018-02-13 下午7:42
 **/
@Component
public class CatalogServiceClient {

    @Autowired
    private RestTemplate restTemplate;

    public CompletableFuture<Product> getProductById(String prodId) {
        return CompletableFuture.supplyAsync(() -> {
            ServiceRequest serviceRequest = new ServiceRequest(restTemplate , CartApplications.getFunctionalUser());
            Map response = serviceRequest.get(Map.class , "http://catalog-service/attributes?prodId={prodId}" , prodId);
            Product product = BeanUtils.mapToModel(response , Product.class);
            return product;
        });
    }

    public CompletableFuture<List<ProductSpec>> getSpecsByProductId(String prodId) {
        return CompletableFuture.supplyAsync(() -> {
            ServiceRequest serviceRequest = new ServiceRequest(restTemplate, CartApplications.getFunctionalUser());
            List response = serviceRequest.get(List.class , "http://catalog-service/specs?prodId={prodId}" , prodId);
            List<ProductSpec> specs = new ArrayList<>();
            for(int i = 0;i<response.size() ; i++){
                ProductSpec productSpec = BeanUtils.mapToModel((Map) response.get(i) , ProductSpec.class);
                specs.add(productSpec);
            }
            return specs;
        });
    }
}
